package com.maxus.mini.data.provider.topic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.alibaba.dubbo.config.annotation.Service;
import com.maux.mini.data.api.topic.TopicService;
import com.maxus.mini.common.ElumClass.EntityState;
import com.maxus.mini.common.utils.BeanUtilsExtended;
import com.maxus.mini.common.PageImplE;
import com.maxus.mini.data.provider.BaseServiceImpl;
import com.maxus.mini.entity.topic.Topic;
import com.maxus.mini.entity.vo.topic.TopicVo;
import com.maxus.mini.repository.topic.TopicRepository;

/**
 * 专题管理
 * 
 * @author wujinsong
 *
 */
@Component()
@Service(version = "1.0.0")
public class TopicServiceImpl extends BaseServiceImpl<Topic, Serializable> implements TopicService<Topic, Serializable> {
	@Autowired
	private TopicRepository<Topic> topicRepository;

	@Override
	public PageImplE<Topic> page(final TopicVo vo) {
		Page<Topic> page = topicRepository.findAll(new Specification<Topic>() {

			@Override
			public Predicate toPredicate(Root<Topic> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<>();
				list.add(cb.equal(root.<String>get("entityState"), EntityState.N.name()));
				
				if (vo.getStatus() != null) {
					list.add(cb.equal(root.<Integer>get("status"), vo.getStatus()));
				}
				
				if (!StringUtils.isEmpty(vo.getQ())) {
					Predicate predicate = cb.like(root.<String>get("name"), "%" + vo.getQ() + "%");
					Predicate predicate2 = cb.like(root.<String>get("intro"), "%" + vo.getQ() + "%");
					Predicate predicate3 = cb.or(predicate, predicate2);
					
					list.add(predicate3);
				}
				
				Predicate[] p = new Predicate[list.size()];
				return cb.and(list.toArray(p));
			}
		}, vo);
		
		PageImplE<Topic> pageImplE = new PageImplE<>();
		BeanUtilsExtended.copyProperties(pageImplE, page);

		return pageImplE;
	}
}
